﻿using System;
using System.IO;
using System.Linq;
using ProjectEuler.Extensions;

namespace ProjectEuler
{
    internal sealed class NumberTriangle
    {
        private readonly Int32[][] _data;

        public NumberTriangle(Int32[][] data)
        {
            _data = data;
        }

        public NumberTriangle(TextReader reader)
        {
            var lines = reader.ReadAllLines().ToArray();
            Array.Reverse(lines);

            _data = new Int32[lines.Length][];

            for (int i = 0; i < lines.Length; i++)
            {
                _data[i] = lines[i].Split(' ').Select(s => Int32.Parse(s)).ToArray();
            }
        }

        public Int32 MaxSum()
        {
            var last = _data[0];

            for (var row = 1; row < _data.Length; row++)
            {
                var current = _data[row];

                for (var i = 0; i < current.Length; i++)
                {
                    var left = current[i];
                    var right = current[i] + last[i + 1];

                    if (i < last.Length)
                    {
                        left += last[i];
                    }

                    current[i] = Math.Max(left, right);
                }

                last = current;
            }

            return last[0];
        }
    }
}
